package com.placement.refresh.service;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rssowl.core.internal.persist.BookMark;
import org.rssowl.core.internal.persist.Description;
import org.rssowl.core.internal.persist.Feed;
import org.rssowl.core.internal.persist.News;
import org.rssowl.core.persist.IFolder;
import org.rssowl.core.persist.INews;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.placement.refresh.dao.RefreshDAO;
import com.placement.refresh.model.AbstractJob;
import com.placement.refresh.model.DiceJob;
import com.placement.refresh.model.Job;
import com.placement.refresh.model.MonsterJob;
import com.placement.refresh.model.RefreshContextBVO;
import com.placement.refresh.model.YahooJob;

/**
 * purpose: This class is service class which executes different steps to
 * retrieve the jobs
 * 
 * @author Amit Chadha
 * 
 */
public class RefreshBatchServiceImpl implements RefreshBatchService {

	private static final Log logger = LogFactory
			.getLog(RefreshBatchServiceImpl.class);

	private RefreshDAO refreshDAO;

	// private TransactionM
	private DataSourceTransactionManager txManager;

	// Default Transaction Definition
	private DefaultTransactionDefinition defTransaction;

	public RefreshDAO getRefreshDAO() {
		return refreshDAO;
	}

	public void setRefreshDAO(RefreshDAO refreshDAO) {
		this.refreshDAO = refreshDAO;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.placement.refresh.service.RefreshBatchService#processJobs
	 */
	public void processJobs() {

		DefaultTransactionDefinition txDef = this.getDefTransaction();
		TransactionStatus status = this.getTxManager().getTransaction(txDef);

		RefreshContextBVO currBatchContext = refreshDAO
				.getCurrBatchRunContext();

		try {
			ArrayList<News> NewsList = this.getJobsData();
			//refreshDAO.saveJobsData(NewsList, 2L);// currBatchContext.getContextId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		this.getTxManager().commit(status);

	}

	public void clearJobDB(Long jobContextId) {
		// TODO Auto-generated method stub

	}

	public DataSourceTransactionManager getTxManager() {
		return txManager;
	}

	public void setTxManager(DataSourceTransactionManager txManager) {
		this.txManager = txManager;
	}

	public DefaultTransactionDefinition getDefTransaction() {
		return defTransaction;
	}

	public void setDefTransaction(DefaultTransactionDefinition defTransaction) {
		this.defTransaction = defTransaction;
	}

	public boolean isProcessCompleted(int processId) {
		return refreshDAO.isProcessCompleted(processId);
	}

	public ArrayList<News> getJobsData() throws Exception {
		ObjectContainer db = null;
		ArrayList<MonsterJob> mjList = new ArrayList<MonsterJob>();
		ArrayList<DiceJob> djList = new ArrayList<DiceJob>();
		ArrayList<YahooJob> yjList = new ArrayList<YahooJob>();
		ArrayList<Job> jobList = new ArrayList<Job>();
		ArrayList<News> NewsList = new ArrayList();
		ArrayList<Feed> FeedsList = new ArrayList();
		ArrayList<BookMark> bookMarksList = new ArrayList();
		try {
			db = Db4o
					.openFile("C:\\Users\\ns_nagar\\runtime-RSSOwl_configuration\\.metadata\\.plugins\\org.rssowl.core\\rssowl.db");

			// Find all the Persons, and give them moods
			ObjectSet jobs = db.get(News.class);

			while (jobs.hasNext()) {

				News job = (News) jobs.next();
				NewsList.add(job);
				/*System.out.print("--- " + job.getfTitle() + " ---\n");
				System.out.print("--- " + job.getfLinkText() + " ---\n");
				System.out.print("--- " + job.getfBaseUri() + " ---\n");
				System.out.print("--- " + job.getfReceiveDate() + " ---\n");
				System.out.print("--- " + job.getfPublishDate() + " ---\n");
				System.out.print("--- " + job.getfModifiedDate() + " ---\n");
				System.out.print("--- " + job.getfComments() + " ---\n");
				System.out.print("--- " + job.getfInReplyTo() + " ---\n");
*/
			}
			System.out.print("Done \n");
			ObjectSet feeds = db.get(Feed.class);
			ObjectSet descriptions = db.get(Description.class);
			ObjectSet bookMarks = db.get(BookMark.class);
			while (bookMarks.hasNext()) {
				
				BookMark bm = (BookMark) bookMarks.next();
				if(isJobparent(bm)){
					bookMarksList.add(bm);
					System.out.print("--- " + "BookMark" + " ---\n");
					System.out.print("--- " + bm.getName() + " ---\n");
					System.out.print("--- " + bm.getMostRecentNewsDate() + " ---\n");
					System.out.print("--- " + bm.getId() + " ---\n");
				}
			}
			while (feeds.hasNext()) {

				Feed feed = (Feed) feeds.next();
				FeedsList.add(feed);
				System.out.print("--- " + "feed" + " ---\n");
				if(feed.getNews().size()>0){
					System.out.print("--- " + feed.getTitle() + " ---\n");
					System.out.print("--- " + feed.getDescription() + " ---\n");
					System.out.print("--- " + feed.getId() + " ---\n");
					System.out.print("--- " + feed.getNews().size() + " ---\n");
					for (INews iNews : feed.getNews()) {
						News news = (News)iNews;
						System.out.print("--- " + news.getfTitle() + " ---\n");
						System.out.print("--- " + news.getfLinkText() + " ---\n");
						System.out.print("--- " + news.getfBaseUri() + " ---\n");
						System.out.print("--- " + news.getfReceiveDate() + " ---\n");
						System.out.print("--- " + news.getfPublishDate() + " ---\n");
						System.out.print("--- " + news.getfModifiedDate() + " ---\n");
						System.out.print("--- " + news.getfComments() + " ---\n");
						System.out.print("--- " + news.getId() + " ---\n");
						for (int i = 0; i < descriptions.size(); i++) {
							Description desc = (Description)descriptions.get(i);
							if(desc.getNews().getId() != 0 && desc.getNews().getId() == news.getId()){
								System.out.print("NewsId: "  + desc.getNews().getId()+" desc " + desc.getValue() + " ---\n");
								if(feed.getTitle() != null &&
										feed.getTitle().startsWith("Monster"))
								{		
									MonsterJob mj = new MonsterJob();
									mj.parseJobData(news, desc);
									mjList.add(mj);
								}
								if(feed.getTitle() != null &&
										feed.getTitle().startsWith("Yahoo"))
								{		
									YahooJob yj = new YahooJob();
									yj.parseJobData(news, desc);
									yjList.add(yj);
								}
								if(feed.getTitle() != null &&
										feed.getTitle().startsWith("Dice"))
								{		
									DiceJob dj = new DiceJob();
									dj.parseJobData(news, desc);
									djList.add(dj);
								}
								
							}
						}
							
					}
				}
			}
			if (mjList.size()>0) jobList.addAll(mjList);
			if (djList.size()>0) jobList.addAll(djList);
			if (yjList.size()>0) jobList.addAll(yjList);

			System.out.print("data Retrieved " + " ---\n");
			for (Job job : jobList) {
				Long zipcode = findZipcode(job.getState(), job.getCity());
				((AbstractJob)job).setZipcode(zipcode);
			}
			refreshDAO.saveJobListing(jobList);	
			
		}

		finally {
			if (db != null)
				db.close();
		}
		return NewsList;
	}


	private Long findZipcode(String state, String city) {
		return refreshDAO.findZipcode(state, city);
	}

	private boolean isJobparent(BookMark bm) {
		IFolder f = bm.getParent();
	
		while (f != null && !"Jobs".equals(f.getName())){
			f = f.getParent();
		}
		if (f != null && "Jobs".equals(f.getName()))
			return true;
		return false;
	}
}